<template>
  <div style="height:100%;width:100%"></div>
</template>

<script>
  import _ from 'lodash'
  import CodeMirror from 'codemirror'
  import './addons'

  const UIThemeOptions = ['base-theme', 'dark']
  const SyntaxThemeOptions = ['default', 'neo', 'eclipse', 'monokai', 'material']

  const debounced = _.debounce(func => func(), 1000)
  const getMode = (tab) => {
    return CodeMirror.findModeByMIME(tab.contentType) || CodeMirror.findModeByFileName(tab.path.split('/').pop())
  }

  export default {
    components: {
    },
    props: {
      theme: { default: 'default' },
      tab: { type: Object }
    },
    data: function () {
      return {
        isChanging: false,
        width: '100%',
        height: '100%',
        editor: {}
      }
    },
    computed: {
    },
    methods: {
      handleChange: function (e) {
        if (!this.isChanging) this.isChanging = true
        this.$store.commit('tab/tabUpdate', {
          id: this.tab.id,
          flags: { modified: true },
          content: { body: this.editor.getValue() }
        })
        if (this.tab.path) debounced(() => {
          // dispatchCommand('file:save')
          this.isChanging = false
        })
      },
      handleFocus: function (e) {
        // this.$store.commit('tab/tabActivate', this.tab.id)
      }
    },
    mounted() {
      const theme = 'default'
      const editor = this.editor = CodeMirror(this.$el, {
        theme: theme,
        lineNumbers: true,
        matchBrackets: true,
        autoCloseBrackets: true
      })
      // @fixme:
      // related counterparts:
      // 1. IdeEnvironment.js
      // 2. commandBindings/file.js
      window.ide.editors[this.tab.id] = editor
      editor.setSize(this.width, this.height)
      // 2. prevent default codemirror dragover handler, so the drag-to-split feature can work
      //    but the default handler that open a file on drop is actually pretty neat,
      //    should make our drag feature compatible with it later
      editor.on('dragover', e => e.preventDefault())
      if (this.tab.content) {
        const body = this.tab.content.body
        const modeInfo = getMode(this.tab)
        if (body) editor.setValue(body)
        if (modeInfo) {
          let mode = modeInfo.mode
          if (mode === 'null') {
            editor.setOption('mode', mode)
          } else {
            require([`codemirror/mode/${mode}/${mode}.js`], () => editor.setOption('mode', mode))
          }
        }
      }
      editor.focus()
      editor.isFocused = editor.hasFocus // little hack to make codemirror work with legacy interface
      editor.on('change', this.handleChange)
      editor.on('focus', this.handleFocus)
    }
  }

</script>
